package org.hibernate.entity;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;


public class HibernateUtil {
    private static SessionFactory sessionFactory;
    private static Configuration configuration;
    private static final ThreadLocal<Session> threadLocal = new ThreadLocal<>();
    static {
        try{
            configuration = new Configuration().configure();
            //ServiceRegistry registry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
            //ServiceRegistry registry2 = new ServiceRegistrybuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
            sessionFactory=configuration.buildSessionFactory();
        }catch (Throwable ex){
            throw new ExceptionInInitializerError(ex);
        }
    }
    public static SessionFactory getSessionFactory(){
        return  sessionFactory;
    }
    public static Session getSession()throws HibernateException{
        Session session=threadLocal.get();
        if(session==null||!session.isOpen()){
            if(sessionFactory==null){
                rebuildSessionFactory();
            }
            session=(sessionFactory!=null)?sessionFactory.openSession():null;
            threadLocal.set(session);
        }
        return session;
    }
    public static void closeSession()throws HibernateException{
        Session session= threadLocal.get();
        threadLocal.set(null);
        if (session!=null){
            session.close();
        }
    }

    public static void rebuildSessionFactory(){
        try{
            configuration.configure("/hibernate.cfg.xml");
            sessionFactory=configuration.buildSessionFactory();
        }
        catch(Exception e){
            System.err.println("Error Creating SessionFactory");
            e.printStackTrace();
        }
    }
    public static void shutdown(){
        getSessionFactory().close();
    }
}
